#include "wefuckapi.h"
#include <QDataStream>
#include <QDebug>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QTimer>
#include "httprequestthread.h"
#include "qrcode.h"
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <iostream>
#include <QStringList>
#include <QSqlRecord>
#include <QQmlApplicationEngine>

using namespace std;

//class HttpRequestThread;

WeFuckApi::WeFuckApi(QObject *parent) : QObject (parent)
{
//    QQmlApplicationEngine engine; // 获取
//    QQmlContext *context = engine.rootContext();
//    context->setContextProperty("frendList", QVariant::fromValue(frendList));
    cookieJar = HttpRequestThread::cookieJar;
    manager.setCookieJar(&HttpRequestThread::cookieJar);// 1question
    QObject::connect(this, &WeFuckApi::wantList, this, &WeFuckApi::getFrendsList);
    QTimer::singleShot(1000, this, SLOT(getFrendsList()));


}

void WeFuckApi::getFrendsList()
{
    QEventLoop loop;
    connect(&manager, &QNetworkAccessManager::finished, &loop, &QEventLoop::quit);
    QDateTime time = QDateTime::currentDateTime();
    QByteArray data;
//    QString uri = QString("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=")
//                                     + QString::number(time.toTime_t())
//                                     + QString("&lang=en_US")
//                                     + QString("&pass_ticket=") + HttpRequestThread::pass_ticket;
    QString uri = QString("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?r=")
                                     + QString::number(time.toTime_t());
    qDebug() << uri;
    QNetworkRequest request((QUrl(uri)));

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QNetworkReply *reply = manager.post(request, data);
//    QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(QString("https://wx.qq.com/webwxgetcontact?r=")+QString(time.toTime_t())+QString("&seq=0&skey="))));
    loop.exec();

//    cout << QString::fromUtf8(reply->readAll()).toStdString();

    QJsonDocument contactJsonDoc(QJsonDocument::fromJson(reply->readAll()));
    QJsonObject contactJson = contactJsonDoc.object();
    QStringList keys = contactJson.keys();

     QJsonArray contactList = contactJson["MemberList"].toArray();

//     QStringList frendList;

     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "sqlite_for_wefuck");
     db.setDatabaseName("wefuckk.db");
     bool ok = db.open();
     qDebug() << "init wefuck:" << ok;
     QSqlQuery insertQuery(db);
     QSqlQuery deleteQuery(db);

     // mkdir
     QDir headerDir(QDir::currentPath() + "/headers/");
     if (!headerDir.exists()) {
         headerDir.mkpath(QDir::currentPath() + "/headers/");
     }

     deleteQuery.exec("DELETE FROM frend_record");
     insertQuery.prepare("INSERT INTO frend_record (user_name, nick_name, head_img_url, sex, remark_name, signature, city) values (?, ?, ?, ?, ?, ?, ?)");
     bool success;

     QStringList tmpFrendList;
     for(QJsonValue o : contactList)
     {
        QJsonObject member = o.toObject();
//         qDebug() << member["NickName"] << ":" << (member["Sex"].toInt() == 2?"woman":"man");

        QString imgUrl = "https://wx.qq.com" + member["HeadImgUrl"].toString().append(HttpRequestThread::skey);
        QEventLoop loop;
        connect(&manager, &QNetworkAccessManager::finished, &loop, &QEventLoop::quit);
        QNetworkReply *reply = manager.get(QNetworkRequest(imgUrl));
        loop.exec();
        QFile imgTmp(QDir::currentPath() + "/headers/" + member["UserName"].toString() + "");
        imgTmp.open(QIODevice::ReadWrite);
//        QDataStream inputStream(reply->readAll());
        imgTmp.write(reply->readAll());

        insertQuery.bindValue(0, member["UserName"].toString());
        insertQuery.bindValue(1, member["NickName"].toString());
        insertQuery.bindValue(2, QFileInfo(imgTmp).absolutePath());
        insertQuery.bindValue(3, member["Sex"].toString());
        insertQuery.bindValue(4, member["RemarkName"].toString());
        insertQuery.bindValue(5, member["Signature"].toString());
        insertQuery.bindValue(6, member["City"].toString());
        success = insertQuery.exec();
        if(!success) {
            QSqlError error = insertQuery.lastError();
            qDebug() << error.driverText();
        } else {
//            qDebug() << "insert successfully";
        }
        tmpFrendList << member["NickName"].toString() + ";;;" + member["UserName"].toString() + ";;;" + "file://" + QDir::currentPath() + "/headers/" + member["UserName"].toString() + "";
        if (tmpFrendList.size() == 15) {
            frendList.clear();
            frendList.append(tmpFrendList);
            frendListChanged();
            tmpFrendList.clear();
        }
    }
     frendList.clear();
     frendList.append(tmpFrendList);
     frendListChanged();
     tmpFrendList.clear();

//     frendModel.fetchMore();
//     frendModel.setQuery("SELECT * FROM frend_record");
//     QQmlApplicationEngine engine;
//     engine.rootContext()->setContextProperty("frendModel", &frendModel);

//     qDebug() << "setQuery";

}

QStringList WeFuckApi::getFrendList() const
{
    return frendList;
}

void WeFuckApi::setFrendList(const QStringList &value)
{
    frendListChanged();
    frendList = value;
}
